package cn.kain.frame;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;

/**
 * @author kai
 * @email kain.wong@foxmail.com
 * @Data 2020年1月3日 下午8:12:44
 * @Description 创建窗口
 * 
 */
public class SwingCreate {

	/**
	 * 创建一个窗口
	 * 
	 * @param f      窗口类
	 * @param width  窗口宽度
	 * @param height 窗口高度
	 * @param title  窗口标题 每一个窗口创建一个线程，使用多线程提升软件响应速度
	 */
	public static void createFrame(final JFrame f, final int width, final int height, String title) {

		Dimension displaySize = Toolkit.getDefaultToolkit().getScreenSize();// 获得显示器大小对象

		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
				if (displaySize.width >= width && displaySize.height >= height) {
					// 设置窗口出现的位置默认居中 (屏幕宽度-窗口宽度)/2=窗口左上角位置出现在屏幕的宽度坐标
					f.setLocation((displaySize.width - width) / 2, (displaySize.height - height) / 2);
				}
				f.setTitle(title);
				// f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
				f.setSize(width, height);
				f.setVisible(true);
			}
		});
	}

	/**
	 * 退出系统
	 */
	public static void SystemClosed(JFrame frame) {
		frame.addWindowListener(new WindowListener() {
			@Override
			public void windowOpened(WindowEvent e) {
			}

			@Override
			public void windowIconified(WindowEvent e) {
			}

			@Override
			public void windowDeiconified(WindowEvent e) {
			}

			@Override
			public void windowDeactivated(WindowEvent e) {
			}

			public void windowClosing(WindowEvent e) {
				frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
			}

			@Override
			public void windowClosed(WindowEvent e) {
			}

			public void windowActivated(WindowEvent e) {
			}
		});
	}

	/**
	 * 点击窗口关闭事件
	 */
	public static void frameClosed(JFrame frame) {
		frame.addWindowListener(new WindowListener() {
			@Override
			public void windowOpened(WindowEvent e) {
			}

			@Override
			public void windowIconified(WindowEvent e) {
			}

			@Override
			public void windowDeiconified(WindowEvent e) {
			}

			@Override
			public void windowDeactivated(WindowEvent e) {
			}

			public void windowClosing(WindowEvent e) {
				frame.dispose(); // 关闭窗口事件
			}

			@Override
			public void windowClosed(WindowEvent e) {
			}

			public void windowActivated(WindowEvent e) {
			}
		});
	}

}
